package com.itheima.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.anno.LogOperation;
import com.itheima.anno.MyLog;
import com.itheima.exception.NotAllowedToDeleteException;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Dept;
import com.itheima.pojo.Emp;
import com.itheima.service.DeptService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService {

/*    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;
    @Override
    @LogOperation
    public List<Dept> selectAllDept(){
        return deptMapper.selectAll();
    }

    @Override
    @LogOperation
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Integer id) {
        //判断部门人数，如果该部门还有人，不允许删除
        Integer count = empMapper.getCountByDeptId(id);
        if(count !=0){
            throw new NotAllowedToDeleteException("对不起，当前部门下有员工，不能直接删除！");
        }
        deptMapper.deleteById(id);
    }

    @Override
    @LogOperation
    public void insertDept(Dept dept) {
        //补全信息
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.insertMapperDept(dept);
    }

    @Override
    @LogOperation
    public Dept selectById(Integer id) {
        return deptMapper.selectMapperById(id);
    }

    @Override
    @LogOperation
    public void updateById(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.updateMapperById(dept);
    }*/

    //Mybatis-plus
    @Autowired
    private EmpService empService;

    //删除部门


    @Override
    public void delete(Integer id) {
        //查找员工表
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        List<Emp> list = empService.list(queryWrapper.eq(Emp::getDeptId, id));
        if (!list.isEmpty()) {
            throw new NotAllowedToDeleteException("该部门下有员工，不能直接删除！");
        }
        //部门下没有员工，直接删除
        this.remove(new LambdaQueryWrapper<Dept>().eq(Dept::getId, id));
    }
}
